import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap, routeModuleList } from '@/router'
import {
  generateRoutesByFrontEnd,
  generateRoutesByServer,
  flatMultiLevelRoutes
} from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { fetchPermission } from '@/api/login'

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
  permissions: AppUserPermissions[]
  permissionCodes: []
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    // 总路由
    routers: [],
    // 添加动态路由数据
    addRouters: [],
    // 是否已添加路由
    isAddRouters: false,
    menuTabRouters: [],
    // 当前登录用户所拥有的权限节点
    permissions: [],
    // 当前登录用户所拥有的权限code
    permissionCodes: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    // oidc获取用户路由和权限
    oidcGenerateRoutes(
      roleId: string,
      // routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>(async (resolve, reject) => {
        const { VITE_APP_CLIENT_ID } = import.meta.env
        try {
          const res = await fetchPermission({ clientId: VITE_APP_CLIENT_ID, roleId })
          console.log('菜单和权限', res)
          let routerMap: AppRouteRecordRaw[] = []
          if (res.code === 0) {
            const { opMenusList, permissionsList } = res.data
            routerMap = dealRoutes(opMenusList)
            const permissionCodes = dealPermissions(permissionsList)

            // console.log('routerMap', opMenusList, permissionsList, permissionCodes)
            this.permissions = permissionsList
            this.permissionCodes = permissionCodes

            const RT:any = cloneDeep([...routeModuleList, ...asyncRouterMap])
            // 动态路由，404一定要放到最后面
            this.addRouters = routerMap.concat(RT).concat([
              {
                path: '/:path(.*)*',
                redirect: '/404',
                name: '404Page',
                meta: {
                  hidden: true,
                  breadcrumb: false
                }
              }
            ])
            // 渲染菜单的所有路由
            this.routers = cloneDeep(RT)
            // 接口动态路由
            // .concat(routerMap)
            // .concat(cloneDeep(asyncRouterMap))

            resolve()
          } else {
            reject()
          }
        } catch (error: any) {
          reject(error.message)
        }
      })
    },
    // 原路由获取
    generateRoutes(
      type: 'server' | 'frontEnd' | 'static',
      routers?: AppCustomRouteRecordRaw[] | string[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = []
        if (type === 'server') {
          // 模拟后端过滤菜单
          routerMap = generateRoutesByServer(routers as AppCustomRouteRecordRaw[])
        } else if (type === 'frontEnd') {
          // 模拟前端过滤菜单
          routerMap = generateRoutesByFrontEnd(cloneDeep(asyncRouterMap), routers as string[])
        } else {
         // 直接读取静态路由表
          routerMap = cloneDeep(asyncRouterMap)
        }
        const RT:any = cloneDeep([...routeModuleList, ...asyncRouterMap])
        // 动态路由，404一定要放到最后面
        this.addRouters =  routerMap.concat(RT).concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        // this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        this.routers = cloneDeep(RT)

        resolve()
      })
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  },
  persist: {
    paths: ['routers', 'addRouters', 'menuTabRouters']
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}

/* Layout */
export const Layout = () => import('@/layout/Layout.vue')

const modulesEager: any = import.meta.glob('../views/**/*.{vue,tsx}')

const modules = Object.keys(modulesEager).reduce((modules, path) => {
  const moduleName = path.replace(/^\.\/modules\/(.*)\.\w+$/, '$1')
  modules[moduleName] = modulesEager[path]?.default
  return modules
}, {})

export interface routeData {
  path: string
  meta: Object
  name: string
  component: Object
}

function dealRoutes(routes) {
  const res: any = []
  routes.forEach((item) => {
    item.nameCn = item.name
    const tmp: any = { ...item }
    if (tmp.parentId === 0) {
      if (tmp.children) {
        tmp.component = Layout
        tmp.redirect =
          tmp.path === '/' ? `/${tmp.children[0].path}` : `${tmp.path}/${tmp.children[0].path}`
        tmp.children = dealRoutes(tmp.children)
      } else {
        const sub_view = tmp.component.replace(/^\/*/g, '')
        const component = `../${sub_view}.vue`
        tmp.component = Layout
        tmp.meta = {
          title: tmp.nameCn,
          hideChild: true
        }
        const tempChildren: routeData[] = []
        tempChildren.push({
          path: tmp.path,
          meta: {
            title: tmp.nameCn
          },
          name: tmp.path.replace(/^\/*/g, ''),
          component: modules[component]
        })
        tmp.children = tempChildren
      }
    } else {
      const sub_view = tmp.component.replace(/^\/*/g, '')
      const component = `../${sub_view}.vue`
      tmp.component = modules[component]
      tmp.name = tmp.path.replace(/^\/*/g, '')
    }
    tmp.title = tmp.nameCn
    tmp.meta = {
      ...tmp?.meta,
      title: tmp.nameCn
    }
    if (!tmp.children) {
      delete tmp.children
    }
    res.push(tmp)
  })
  return res
}

function dealPermissions(permissionsList) {
  const res = permissionsList.map((tmp) => {
    return tmp.code
  })
  return res
}
